package tjs.org.springLoader.reloader;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.ProtectionDomain;

/**
 * Created by Nicky.Tang on 2021/9/30 9:53 上午
 *
 * @since 02.12.10
 */
public class ChangeClassReloader extends ClassLoader {

    private static Method doDefineClass = initDoDefineClassMethod();

    public ChangeClassReloader() {
    }

    public static Method initDoDefineClassMethod() {
        Method doDefineClass = null;
        try {
            doDefineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class, ProtectionDomain.class);
            doDefineClass.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return doDefineClass;
    }

    public static Class<?> defineClass(String beanClassName, byte[] newClassBytes) {
        ChangeClassReloader classLoader = new ChangeClassReloader();
        try {
            return (Class<?>) ChangeClassReloader.doDefineClass.invoke(classLoader, beanClassName, newClassBytes, 0, newClassBytes.length, null);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
